<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/11/10
 * Time: 15:48
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\admin\exception;

use app\common\lib\Show;
use app\common\lib\Status;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

class Http extends Handle
{
    public function render($request, Throwable $e): Response
    {

        if ($e instanceof ValidateException) {
            return Show::json_show(Status::status_error, $e->getError());
        }

        // 请求异常
        if ($e instanceof HttpException && $request->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }
        // 其他错误交给系统处理
        if (env('app_debug', false)) {
            return parent::render($request, $e);
        } else {
            $type = $this->getResponseType();
            if ($type == 'html') {
                return Response::create(app_path('view/layout') . "500.html", "view",$e->getCode())->assign(['msg' => $e->getMessage()])->header([]);
            } else {
                return Show::json_show(Status::status_error, $e->getMessage());
            }
        }
    }

    protected function getResponseType()
    {
        return (request()->isJson() || request()->isAjax() || request()->isPost()) ? 'json' : 'html';
    }
}